{% load crispy_forms_tags %}
{% load static %}
{% block extrastyle %}
<link rel="stylesheet" href="{% static 'bootstrap/css/bootstrap.min.css' %}">
<link rel="stylesheet" type="text/css" href="{ % static 'css/user_task_form.css' % }"/>
{% endblock extrastyle %}

<div class="print-content">
  <button type="button" class="btn btn-secondary" onclick="window.print()">Print Form</button>
</div>

<form id="taskForm" method="post" action="{% url 'workflow:run' workflow.id task.id %}" class="needs-validation" enctype="multipart/form-data">
  {% csrf_token %}
  <div class="card">
    <div class="card-body">
      <div class="form-row">
        {% for field in form %}
        <div class="col-md-4 mb-3">
          <div class="form-group">
            {{ field|as_crispy_field }}
            {% if field.errors %}
            <div class="field-errors">
              {{ field.errors }}
            </div>
            {% endif %}
          </div>
        </div>
        {% endfor %}
      </div>
      <div class="button-container">
        <button type="submit" class="btn btn-danger">Submit</button>
        {% for event in signal_buttons %}
        {% if event.task_id == task.id %}
        <button type="button" class="btn btn-primary" onclick="fireSignal('{{ event.button_label }}', '{{ workflow.id }}')">
          {{ event.button_label }}
        </button>
        {% endif %}
        {% endfor %}
      </div>
    </div>
  </div>
</form>
{% if task_has_active_timer %}
<!-- Countdown Timer Display -->
<div id="countdown" class="alert alert-info mt-3"></div>

<script>
    document.addEventListener("DOMContentLoaded", function () {
        let remainingTime = {{ remaining_time }};  // Remaining time in seconds from the backend

        function updateCountdown() {
            if (remainingTime <= 0) {
                document.getElementById("countdown").innerText = "Timer expired!";
                return;
            }

            const minutes = Math.floor(remainingTime / 60);
            const seconds = remainingTime % 60;
            document.getElementById("countdown").innerText = `${minutes}m ${seconds}s remaining`;
            remainingTime--;
        }

        updateCountdown();
        setInterval(updateCountdown, 1000);  // Update every second
    });
</script>
{% endif %}

<script>
  document.addEventListener("DOMContentLoaded", function() {
    const socket = new WebSocket('ws://' + window.location.host + '/notifications/');

    socket.onmessage = function(event) {
      const data = JSON.parse(event.data);
      if (data.type === 'tag_added') {
        console.log(data.message); 
      }
    };
  });

  function fireSignal(buttonLabel, workflowId) {
    const url = "{% url 'workflow:trigger_signal' %}";
    const csrfToken = '{{ csrf_token }}';
    let signal = '';

    if (buttonLabel === 'Edit') {
      signal = 'edit_manual_form';
    } else if (buttonLabel === 'Reject') {
      signal = 'reject_iv_admin';
    } else {
      signal = buttonLabel;
    }

    const requestData = {
      workflow_id: workflowId,
      button_label: signal,
    };

    console.log('Request Data:', requestData);

    fetch(url, {
      method: 'POST',
      headers: {
        'X-CSRFToken': csrfToken,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(requestData),
    })
    .then((response) => {
      if (response.ok) {
        document.getElementById('taskForm').submit();
      } else {
        response.json().then((data) => {
          alert('Error sending signal: ' + data.message);
        });
      }
    })
    .catch((error) => {
      console.error('Error:', error);
      alert('Error sending signal.');
    });
  }
</script>

<script src="{% static 'bootstrap/js/bootstrap.min.js' %}"></script>
